package com.lagou.task19;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientStringTest {
    public static void main(String[] args) {
        Socket s = null;
        PrintStream ps = null;
        Scanner sc = new Scanner(System.in);
        BufferedReader br = null;
        try {
//        1创建Socket类型的对象并提供服务器的ip和端口
            s = new Socket("127.0.0.1",8888);
            System.out.println("连接服务器成功");
            System.out.println("请输入需要发送的内容");
            ps = new PrintStream(s.getOutputStream());
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            while (true) {
                String msg = sc.next();
//        2使用输入输出流进行通信
//            Thread.sleep(5000);
                ps.println(msg);
                System.out.println("客户端发送数据内容成功");
                //打印服务端回复的内容
                String msg1 = br.readLine();
                System.out.println("服务器发来的信息：" + msg1);
                if ("bye".equalsIgnoreCase(msg)){
                    System.out.println("聊天结束，关闭客户端");
                    break;
                }
            }
        } catch (IOException /*| InterruptedException*/ e) {
            e.printStackTrace();
        } finally {
//        3关闭Socket并释放相关资源
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ps){
                ps.close();
            }
        }

    }
}
